import 'package:flutter/material.dart';
import 'package:event_bus/event_bus.dart';

/// 1. 创建全局 eventBus 对象
final eventBus = EventBus();

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Provider")),
        body: MyBody(),
      ),
    );
  }
}

class MyBody extends StatelessWidget {
  const MyBody({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [MyButton(), MyText()],
      ),
    );
  }
}

class MyButton extends StatefulWidget {
  const MyButton({Key? key}) : super(key: key);

  @override
  State<MyButton> createState() => _MyButtonState();
}

class _MyButtonState extends State<MyButton> {
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
        onPressed: () {
          /// 2. 发出事件
          eventBus.fire("按下按钮");
        },
        child: Text(
          "Button",
          style: TextStyle(fontSize: 20),
        ));
  }
}

class MyText extends StatefulWidget {
  const MyText({Key? key}) : super(key: key);

  @override
  State<MyText> createState() => _MyTextState();
}

class _MyTextState extends State<MyText> {
  String _msg = "MMMMMMMMMM";

  @override
  void initState() {
    super.initState();

    /// 3. 监听事件类型 一般不会监听 String，去监听自定义的类型
    eventBus.on<String>().listen((event) {
      setState(() {
        _msg = event;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text(
        _msg,
        style: TextStyle(fontSize: 20),
      ),
    );
  }
}
